package client;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;

public class ClientTransport {
    private String ip;
    private int port;

    private DataOutputStream out;
    private DataInputStream in;
    private Socket socket;

    public ClientTransport(String ip, int port) throws ConnectException {
        try {
            this.ip = ip;
            this.port = port;
            this.socket = new Socket(ip, port);
            System.out.println("Successful connect to server ip:" + ip + ", port: " + port);
            this.out = new DataOutputStream(this.socket.getOutputStream());
            this.in = new DataInputStream(this.socket.getInputStream());
        } catch (ConnectException e) {
            System.out.println("Connection timed out");
            System.exit(1);
        }
        catch (Exception e) {
        }
    }

    public boolean tryToReconnect () {
        try {
            this.socket = new Socket(ip, port);
            System.out.println("Successful connect to server ip:" + ip + ", port: " + port);
            this.out = new DataOutputStream(this.socket.getOutputStream());
            this.in = new DataInputStream(this.socket.getInputStream());
            return true;
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
    }

    public void writeLine(String line) throws IOException {
        out.writeUTF(line);
        out.flush();
    }

    public String readLine() throws IOException {
        String str =  in.readUTF();
        return str;
    }

    public void close() {
        if (!socket.isClosed()) {
            try {
                in.close();
                out.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
